package run.jingjing.websocket.timer;

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import run.jingjing.websocket.model.LWsGroup;
import run.jingjing.websocket.model.LWsTopic;
import run.jingjing.websocket.template.WebSocketTemplate;
import run.jingjing.websocket.endpoint.AbstractWebSocketEndpoint;
import run.jingjing.websocket.model.RunningTopic;
import java.util.concurrent.TimeUnit;

/**
 * @author: jingjing
 * @date: 2021/6/24
 * @description:
 */
public class BroadcastOnlineCountTask implements TimerTask {

    private RunningTopic runningTopic;

    private WebSocketTemplate webSocketTemplate;

    private HashedWheelTimer timer;

    private Integer intervalSecond;

    public BroadcastOnlineCountTask(RunningTopic runningTopic, WebSocketTemplate webSocketTemplate, HashedWheelTimer timer, Integer intervalSecond) {
        this.runningTopic = runningTopic;
        this.webSocketTemplate = webSocketTemplate;
        this.timer = timer;
        this.intervalSecond = intervalSecond;
    }

    @Override
    public void run(Timeout timeout) {
        LWsTopic topic = runningTopic.getlWsTopic();
        LWsGroup group = runningTopic.getlWsGroup();
        Integer countOnline = webSocketTemplate.countOnline(group.getName(), topic.getName());
        topic.entrySet().forEach(i -> {
            if (i.getValue().getSession().isOpen()) {
                String msgText = String.format("{\"sign\": \"%s\",\"value\": %d}", AbstractWebSocketEndpoint.MsgSign.OnlineCount, countOnline);
                webSocketTemplate.publish(runningTopic, AbstractWebSocketEndpoint.PublishEvent.BROADCAST, msgText, null, null);
            }
        });
        Timeout newTimeout = timer.newTimeout(this, intervalSecond, TimeUnit.SECONDS);
        runningTopic.removeTimeout(timeout);
        runningTopic.addTimeouts(newTimeout);
    }
}
